import axios from 'axios';
import storageutils from '../utils/storageutils';
import {MessageBox, Indicator} from 'mint-ui';
import router from '../router'


axios.defaults.timeout = 20000;//20秒
// axios.defaults.baseURL = 'http://192.168.10.201:88';
axios.defaults.baseURL = 'http://www.sfdgyl.com:8080';


//http request 拦截器
axios.interceptors.request.use(
  config => {
    console.log('http request interceptor');
    let token = storageutils.getToken() || '';
    config.headers.token = token; //所有连接都自动带上token验证
    Indicator.open({
      text: '加载中',
      // spinnerType: 'fading-circle'
    });
    return config;
  },
  error => {
    Indicator.close();
    return Promise.reject(err);
  }
)

//http response 拦截器
axios.interceptors.response.use(
  response => {
    console.log(response);
    console.log('-------------');
    if(response.data.code == 401){//token 失效
      router.push("/login");
    }
    return response;
  },
  error => {
    Indicator.close();
    return Promise.reject(error)
  }
)


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }).then(response => {
      Indicator.close();
      resolve(response.data)
    }).catch(err => {
        Indicator.close();
        reject(err)
      }
    )
  })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
          Indicator.close();
          resolve(response.data)
        },
        err => {
          Indicator.close();
          reject(err)
        }
      )
  })
}



